<template>
  <div class="login-container">
    <ForgetPasswordModal
      @onClose="forgetPasswordVisible = false"
      append-to-body
      :dialog-visible="forgetPasswordVisible"
    />
    <div class="main">
      <div class="login-header">
        <div class="header-content">
          <a href="/">
            <img
              src="@/assets/images/zm_logo1.png"
              alt=""
              class="logo"
            />
          </a>
          <div class="hot-line">
            <img src="@/assets/images/phone.png" /><label data-v-1e6c56df="">{{webSiteInfo.hotline}}</label>
          </div>
        </div>
      </div>
      <div class="main-center">
        <div class="login-form-wrapper">
          <div class="left">
            <!-- <ImageWithLoading :loading="imgLoading">
          <img class="banner" :src="webSiteInfo.loginPageBanner" />
        </ImageWithLoading> -->
            <img
              class="banner"
              src="@/assets/images/leftLogo.png"
            />
          </div>
          <el-form
            ref="loginRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @submit.prevent="onSubmit"
          >
            <div v-if="loginType === LoginTypeEnum.EMPTY">
              <h3 class="title" style="font-weight: 900;">州孟科技众包平台</h3>
              <div class="tabs">账号登录</div>
              <el-form-item prop="username">
                <el-input
                  @blur="handleBlur"
                  v-model="loginForm.username"
                  type="text"
                  size="large"
                  auto-complete="off"
                  placeholder="账号"
                >
                  <template #prefix>
                    <img
                      src=""
                      alt=""
                      class="prefix-icon"
                    >
                  </template>
                  <template
                    v-if="loadingProvider"
                    #suffix
                  >
                    <el-icon class="is-loading">
                      <Loading />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  size="large"
                  auto-complete="off"
                  placeholder="密码"
                  @keyup.enter="firstLogin"
                >
                  <template #prefix>
                    <img
                      data-v-529c61aa=""
                      src=""
                      class="prefix-icon"
                      alt=""
                    >
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                prop="sydId"
                v-if="providerList.length > 0"
              >
                <el-select
                  v-model="loginForm.sydId"
                  placeholder="请选择服务商"
                  style="width: 100%"
                  @change="sydChange"
                >
                  <el-option
                    v-for="item in providerList"
                    :key="item.sydId"
                    :label="item.sydName"
                    :value="item.sydId"
                  ></el-option>
                  <template #prefix><svg-icon
                      icon-class="company"
                      class="el-input__icon input-icon"
                    /></template>
                </el-select>
              </el-form-item>
              <el-form-item
                prop="tenantId"
                v-if="tenantEnabled"
              >
                <el-select
                  v-model="loginForm.tenantId"
                  filterable
                  placeholder="请选择/输入公司名称"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in tenantList"
                    :key="item.tenantId"
                    :label="item.companyName"
                    :value="item.tenantId"
                  ></el-option>
                  <template #prefix><svg-icon
                      icon-class="company"
                      class="el-input__icon input-icon"
                    /></template>
                </el-select>
              </el-form-item>
              <el-form-item
                prop="code"
                v-if="captchaEnabled"
              >
                <el-input
                  v-model="loginForm.code"
                  size="large"
                  auto-complete="off"
                  placeholder="验证码"
                  style="width: 63%"
                  @keyup.enter="firstLogin"
                >
                  <template #prefix>
                    <img
                      data-v-529c61aa=""
                      src=""
                      class="prefix-icon"
                      alt=""
                    >
                  </template>
                </el-input>
                <div class="login-code">
                  <img
                    :src="codeUrl"
                    @click="getCode"
                    class="login-code-img"
                  />
                </div>
              </el-form-item>
              <!--
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          -->
              <el-form-item style="float: left;">
                <!-- <el-button circle title="微信登录" @click="doSocialLogin('wechat')">
              <svg-icon icon-class="wechat" />
            </el-button>
            <el-button circle title="MaxKey登录" @click="doSocialLogin('maxkey')">
              <svg-icon icon-class="maxkey" />
            </el-button>
            <el-button circle title="Gitee登录" @click="doSocialLogin('gitee')">
              <svg-icon icon-class="gitee" />
            </el-button>
            <el-button circle title="Github登录" @click="doSocialLogin('github')">
              <svg-icon icon-class="github" />
            </el-button> -->
                <el-link
                  type="primary"
                  @click="openForgetModal"
                >忘记密码?</el-link>
              </el-form-item>
              <el-form-item style="width:100%;">
                <el-button
                  class="loginBtn"
                  :loading="loading"
                  size="large"
                  type="primary"
                  style="width:100%;"
                  @click.prevent="firstLogin"
                  :disabled="canLogin"
                >
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
                <div
                  style="float: right;"
                  v-if="register"
                >
                  <router-link
                    class="link-type"
                    :to="'/register'"
                  >立即注册</router-link>
                </div>
              </el-form-item>
            </div>

            <div
              style="transform: translateY(-60%)"
              v-if="loginType === LoginTypeEnum.MESSAGE"
            >
              <p class="title" style="font-weight: 800;">短信验证：{{firstLoginReturnedData.phone}}</p>
              <el-row :gutter="6">
                <el-col>
                  <el-form-item prop="smsCode">
                    <el-input
                      placeholder="请输入短信验证码"
                      v-model="loginForm.smsCode"
                      autofocus
                      @keyup.enter="handleLogin"
                    >
                      <template #prefix>
                        <img
                          style="width: 12px"
                          src=""
                        />
                      </template>
                      <template #append>
                        <el-button
                          @click="getValidateCode"
                          :disabled="(restSecond < 60 && restSecond > 0) || !firstLoginReturnedData.phone"
                        >获取验证码
                          <span v-if="![0, 60].includes(restSecond)">{{restSecond}}s</span>
                        </el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row style="margin-top:10px;">
                <el-col :span="24">
                  <el-button
                    :loading="loading"
                    style="width: 100%"
                    type="primary"
                    size="large"
                    @click.prevent="handleLogin"
                  > 确定 </el-button>
                </el-col>
              </el-row>
            </div>
            <div v-if="loginType === LoginTypeEnum.WE_CHAT">
              <p class="title" style="font-weight: 800;">微信扫码验证</p>
              <el-divider>扫码验证 即可登录</el-divider>
              <div id="wxqrcode-container">
                <!-- <div v-if="!wxPubResult.qrCode">验证码获取失败，请稍后重试</div> -->
                <div class="wx-code-container">
                  <img
                    style="width:200px;height:200px;"
                    :src="wxPubResult.qrcode"
                    alt=""
                  />
                  <!-- <img
                :src="wxPubResult.qrcode || ''"
                alt=""
              /> -->
                  <div style="font-size: 12px;">
                    <i
                      aria-label="图标: wechat"
                      class="anticon anticon-wechat"
                    >
                      <svg
                        viewBox="64 64 896 896"
                        data-icon="wechat"
                        width="1em"
                        height="1em"
                        fill="rgb(48, 183, 53)"
                        aria-hidden="true"
                        focusable="false"
                        class=""
                      >
                        <path d="M690.1 377.4c5.9 0 11.8.2 17.6.5-24.4-128.7-158.3-227.1-319.9-227.1C209 150.8 64 271.4 64 420.2c0 81.1 43.6 154.2 111.9 203.6a21.5 21.5 0 0 1 9.1 17.6c0 2.4-.5 4.6-1.1 6.9-5.5 20.3-14.2 52.8-14.6 54.3-.7 2.6-1.7 5.2-1.7 7.9 0 5.9 4.8 10.8 10.8 10.8 2.3 0 4.2-.9 6.2-2l70.9-40.9c5.3-3.1 11-5 17.2-5 3.2 0 6.4.5 9.5 1.4 33.1 9.5 68.8 14.8 105.7 14.8 6 0 11.9-.1 17.8-.4-7.1-21-10.9-43.1-10.9-66 0-135.8 132.2-245.8 295.3-245.8zm-194.3-86.5c23.8 0 43.2 19.3 43.2 43.1s-19.3 43.1-43.2 43.1c-23.8 0-43.2-19.3-43.2-43.1s19.4-43.1 43.2-43.1zm-215.9 86.2c-23.8 0-43.2-19.3-43.2-43.1s19.3-43.1 43.2-43.1 43.2 19.3 43.2 43.1-19.4 43.1-43.2 43.1zm586.8 415.6c56.9-41.2 93.2-102 93.2-169.7 0-124-120.8-224.5-269.9-224.5-149 0-269.9 100.5-269.9 224.5S540.9 847.5 690 847.5c30.8 0 60.6-4.4 88.1-12.3 2.6-.8 5.2-1.2 7.9-1.2 5.2 0 9.9 1.6 14.3 4.1l59.1 34c1.7 1 3.3 1.7 5.2 1.7a9 9 0 0 0 6.4-2.6 9 9 0 0 0 2.6-6.4c0-2.2-.9-4.4-1.4-6.6-.3-1.2-7.6-28.3-12.2-45.3-.5-1.9-.9-3.8-.9-5.7.1-5.9 3.1-11.2 7.6-14.5zM600.2 587.2c-19.9 0-36-16.1-36-35.9 0-19.8 16.1-35.9 36-35.9s36 16.1 36 35.9c0 19.8-16.2 35.9-36 35.9zm179.9 0c-19.9 0-36-16.1-36-35.9 0-19.8 16.1-35.9 36-35.9s36 16.1 36 35.9a36.08 36.08 0 0 1-36 35.9z"></path>
                      </svg></i>
                    微信绑定扫码登录
                  </div>
                </div>
              </div>
              <!--
          <div style="display: flex;justify-content: end;margin-top: 20px;">
            <el-link type="primary" @click="openForgetModal">忘记密码</el-link>
          </div> -->
            </div>
          </el-form>
        </div>
        <div class="text">众包 / 分包 / 兼职 / 临时人员 / 佣金结算</div>
      </div>
      <!--  底部  -->
      <div class="el-login-footer">
        <span>{{webSiteInfo.copyright}}</span>
        <a
          :href="webSiteInfo.copyrightUrl"
          target="blank"
          class="copy-right-url"
        >豫ICP备2023032830号-1</a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList, tlogin, loginSmsCode, loginWxPubCode, loginWxPubResult } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus, LoginTypeEnum } from '@/enums/RespEnum';
import { useAppStore } from '@/store/modules/app';
import ImageWithLoading from './ImageWithLoading.vue';
import ForgetPasswordModal from './ForgetPasswordModal.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const appStore = useAppStore();
const webSiteInfo = computed(() => appStore.webSiteInfo);
const imgLoading = computed(() => !webSiteInfo.value.loginPageBanner);
const canLogin = ref(true);
window.flag = true;

const router = useRouter();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
  sydId: '',
  smsCode: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
  smsCode: [{ required: true, trigger: 'change', message: '请输入短信验证码' }]
};

const onSubmit = () => {};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(false);
const loadingProvider = ref(false);

const providerList = ref<any[]>([]);
const wxPubResult = ref({ qrcode: '', id: '' });

const firstLoginReturnedData = ref<any>({});

const loginType = ref<LoginTypeEnum>(LoginTypeEnum.EMPTY);
const restSecond = ref<number>(60);

// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();
const forgetPasswordVisible = ref(false);

const openForgetModal = () => {
  forgetPasswordVisible.value = true;
};
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

let timer: number;

const getValidateCode = async () => {
  restSecond.value = 60;
  proxy?.$modal.msg('验证码发送中...');
  timer = setInterval(() => {
    restSecond.value -= 1;
    if (restSecond.value === 0) {
      clearInterval(timer);
    }
  }, 1000);

  const { origin } = window.location;
  const [err, res] = await to(loginSmsCode({ domain: origin, id: firstLoginReturnedData.value.id }));
  if (err) {
  }
};

const firstLogin = () => {
  if (!window.flag) {
    handleLogin();
    return;
  }
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      loading.value = true;
      const [err, res] = await to(tlogin(loginForm.value));
      loading.value = false;
      if (err) {
        getCode();
      }
      const { code, data } = res as any;
      if (code === 200) {
        firstLoginReturnedData.value = data;
        loginType.value = data.loginType;
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

const handleBlur = async () => {
  loginForm.value.sydId = null;
  canLogin.value = true;
  if (!loginForm.value.username) {
    return;
  }
  loadingProvider.value = true;
  const [err, res] = await to(userStore.getMerchantProvider(loginForm.value.username || ''));
  loadingProvider.value = false;
  const { code } = res || {};

  const data = res?.data || [];
  if (code === HttpStatus.SUCCESS) {
    providerList.value = data;
    if (!res.data) {
      canLogin.value = false;
    }
  } else {
    ElMessage.error('获取失败');
  }
};

const sydChange = (val) => {
  canLogin.value = false;
};

const handleLogin = () => {
  if (canLogin.value) {
    return;
  }

  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 调用action的登录方法
      const submitData = {
        // smsCode: loginForm.value.smsCode,
        ...loginForm.value,
        id: firstLoginReturnedData.value.id,
        sydId: firstLoginReturnedData.value.sydId
      };

      if (loginType.value === LoginTypeEnum.MESSAGE) {
        submitData.grantType = 'sms';
      } else if (loginType.value === LoginTypeEnum.WE_CHAT) {
        submitData.grantType = 'weixinpub';
      }
      const [err] = await to(userStore.login(submitData));
      if (!err) {
        await router.push({ path: redirect.value || '/' });
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (loginType.value === LoginTypeEnum.EMPTY) {
          if (captchaEnabled.value) {
            await getCode();
          }
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();

  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

//检测租户选择框的变化
watch(
  () => loginForm.value.tenantId,
  () => {
    localStorage.setItem('tenantId', String(loginForm.value.tenantId));
  }
);

let checkWxPubResultTimer: number;
let seconds = 0;

const getWxPubResult = () => {
  seconds = 0;
  checkWxPubResultTimer = setInterval(() => {
    seconds++;
    loginWxPubResult({ id: wxPubResult.value.id })
      .then(
        (res) => {
          const { code, data } = res;
          if (code === 200 && data && data.access_token) {
            clearInterval(checkWxPubResultTimer);
            console.log('------------');
            userStore.setPlatFormToken(data.access_token);
            router.push({ path: redirect.value || '/' });
            // router.push('/')
          }
        },
        (res) => {
          loginType.value = LoginTypeEnum.EMPTY;
          clearInterval(checkWxPubResultTimer);
          getCode();
        }
      )
      .finally(() => {
        console.log(seconds);
        if (seconds > 600) {
          loginType.value = LoginTypeEnum.EMPTY;
          clearInterval(checkWxPubResultTimer);
          getCode();
        }
      });
  }, 1000);
};

// 监听登录验证方式
watch(
  () => loginType.value,
  () => {
    if (!loginType.value) return;
    // 微信验证登录
    if (loginType.value === 2) {
      const submitData = {
        id: firstLoginReturnedData.value.id,
        sydId: firstLoginReturnedData.value.sydId,
        domain: origin
      };
      loginWxPubCode(submitData)
        .then((res) => {
          const { code } = res;
          if (code === HttpStatus.SUCCESS) {
            wxPubResult.value = res?.data;
            getWxPubResult();
          } else {
            ElMessage.error('二维码获取失败');
          }
        })
        .catch(() => {
          ElMessage.error('二维码获取失败');
        });
    }
  }
);

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  height: 100%;
  background-image: url('../assets/images/login-background.png');
  background-color: #f3f3f3;
  background-size: cover;
  overflow: hidden;
  .login-header {
    position: absolute;
    top: 0px;
    height: 12%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    color: #fff;
    // background-color: #fff;
    .header-content {
      margin: 0 auto;
      width: 75%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 5px;
      .logo {
        // height:70px;
        width: 55%;
        vertical-align: top;
        margin-right: 16px;
        border-style: none;
      }
    }
  }

  .hot-line {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 18px;
    color: #fff;

    img {
      vertical-align: middle;
      border-style: none;
      margin-right: 10px;
      width: 26px;
    }
  }
}
.main {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  .main-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 70%;
    height: 65%;

    .text {
      color: #fff;
      font-size: 18px;
      font-weight: bold;
      text-shadow: 0px 5px 5px #4e4c4c;
      text-align: center;
      margin-top: 20px;
    }
  }
}
.login-form-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0px 0px 20px #999;
  .left {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
    .banner {
      display: block;
      width: 80%;
    }
  }
}

.title {
  margin: 0px auto 20px auto;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #4e4c4c;
}
.login-form {
  padding: 40px 0;
  background: #ffffff;
  width: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  .tabs {
    width: 79px;
    font-size: 17px;
    color: #131313;
    line-height: 40px;
    text-align: center;
    margin-bottom: 20px;
    &::after {
      content: '';
      display: block;
      width: 79px;
      height: 4px;
      background-color: #1a85ff;
    }
  }

  & > div {
    width: 80%;
  }
  .el-input {
    flex: 1;
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
  .prefix-icon {
    width: 14px;
    margin-left: 0px;
  }
  .el-link {
    color: #1a85ff;
  }
  .loginBtn {
    height: 50px;
    background-color: #4f93fe;
    border: solid 1px #1a72fe;
    border-radius: 60px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  height: 40px;
  display: flex;
  justify-content: end;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  line-height: 30px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;

  .copy-right-url {
    color: #fff;
    margin-left: 5px;
  }
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
  width: 100%;
}

#wxqrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  .wx-code-container {
    padding: 15px;
    box-shadow: 0 1px 16px 0 #c0c8e6;
  }
  & > div {
    text-align: center;
  }
}
</style>
